package com.mebius.sys.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.mebius.common.service.BaseService;
import com.mebius.common.utils.BeanUtils;
import com.mebius.common.utils.security.Md5Utils;
import com.mebius.common.web.model.DataTable;
import com.mebius.common.web.model.Pager;
import com.mebius.sys.entity.User;
import com.mebius.sys.service.UserService;
import com.mebius.sys.web.dto.UserDto;

@Service
public class UserServiceImpl extends BaseService<User> implements UserService {

	@Override
	public void add(UserDto dto) {
		User user = new User() ;
		BeanUtils.copyNotNullProperties(dto, user) ;
		user.randomSalt();
		user.setPassword(encryptPassword(user.getUsername(), user.getPassword(), user.getSalt())) ;
		
		this.hibernate.add(user);
	}
	private String encryptPassword(String username, String password, String salt) {
        return Md5Utils.hash(username + password + salt);
    }

	@Override
	public void delete(int id) {
		this.hibernate.delete(User.class, id) ;
	}

	@Override
	public void update(UserDto dto) {
		User user = this.hibernate.get(User.class, dto.getId()) ;
		this.hibernate.update(user) ;
	}

	@Override
	public UserDto get(UserDto dto) {
		User user = this.hibernate.get(User.class, dto.getId()) ;
		BeanUtils.copyNotNullProperties(user, dto) ;
		return dto ;
	}

	@Override
	public DataTable datagrid(UserDto dto) {
		Pager<UserDto> p = this.find(dto) ;
		
		DataTable d = new DataTable() ;
		d.setAaData(p.getDataRows()) ;
		d.setiTotalRecords(p.getTotalNumber()) ;
		d.setiTotalDisplayRecords(p.getTotalNumber()) ;
		
		return d;
	}
	
	private Pager<UserDto> find(UserDto dto) {
		
		Map<String, Object> alias = new HashMap<String, Object>();
		String sql = "select t.* from sys_user t where 1=1";
		sql = addWhere(sql, dto, alias) ;
		return this.hibernate.findSQL(sql, alias, User.class, true) ;
		
	}
	
	private String addWhere(String sql, UserDto dto, Map<String, Object> params) {
		if (null != dto) {
			if (dto.getId() != null) {
				sql += " and t.id=:id";
				params.put("id", dto.getId());
			}
			if(dto.getSSearch() != null && !"".equals(dto.getSSearch())){
				sql += " and (t.username like '%%" + dto.getSSearch() + "%%' or t.email like '%%" + dto.getSSearch() + "%%')";
			}
			
		}
		return sql;
	}
	
	

}
